import {View, TouchableOpacity, Text, ToastAndroid, StyleSheet} from 'react-native';
import {
  requestPermissions, // 请求设备权限
  scanDevice, // 开始扫描设备
  BluetoothBatteryLevel, // 返回信号强度
  connectAndDiscoverServices, // 连接设备获取设备电量,然后断开连接(断开连接逻辑在工具包里面)
  stopScan, // 停止扫描
  disconnectDevice, // 断开连接
  updateBikeStatus
} from '@/utils/ble';
import { useState} from 'react';
import { Characteristic, Device } from 'react-native-ble-plx';
import { BluetoothCtrlBikeCommandEnum } from '@/constants/BluetoothEnum';
import IconButton from '@/components/IconButton';

export default function App() {
  const [dataArr, setDataArr] = useState([]); // 设备列表
  const [connectedDevice, setConnectedDevice] = useState<Device>(); // 连接上的蓝牙设备
  const [characteristic, setCharacteristic] = useState<Characteristic>(); // 蓝牙设备特征值

  // 更新设备数据(已经到扫描到的不会重复添加)
  function devicesArr(str) {
    let newData = str;
    let found = false;
    setDataArr(arr => {
      arr = arr.map(item => {
        if (item.name === newData.name) {
          found = true;
          return {...item, xinhao: newData.xinhao};
        }
        return item;
      });
      if (!found) {
        arr.push(newData);
      }
      return arr;
    });
  }

  // 扫描设备
  const scanDevices = async () => {
    // 请求权限
    await requestPermissions(res => {
      console.log('开始扫描设备');
      scanDevice((error, scannedDevice) => {
        if (error) {
          console.error('扫描错误:', error);
          return;
        }
        devicesArr({
          name: scannedDevice.name,
          xinhao: BluetoothBatteryLevel(scannedDevice.rssi),
          devices: scannedDevice,
        });
      });
    });
  };

  // 连接设备
  async function connectDevice(item: {devices: Device}) {
    await connectAndDiscoverServices(
      item.devices,
      (flag: boolean, characteristic: Characteristic) => {
        if(flag) {
          setConnectedDevice(item.devices)
          setCharacteristic(characteristic)
        }
      },
    );
  }

  async function cancelConnectDevice() {
    await disconnectDevice(connectedDevice.id, (flag: boolean) => {
      if(flag) {
        setConnectedDevice(null)
        setCharacteristic(null)
        ToastAndroid.show('操作成功!', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show('操作失败!', ToastAndroid.SHORT);
      }
    })
  }
  // 启动车辆
  function startBike() {
    updateBikeStatus(characteristic!, BluetoothCtrlBikeCommandEnum.启动, (flag: boolean) => {
      if(flag) {
        ToastAndroid.show('启动成功!', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show('启动操作失败!', ToastAndroid.SHORT);
      }
    })
  }
  // 锁车
  function lockBike() {
    updateBikeStatus(characteristic!, BluetoothCtrlBikeCommandEnum.锁车, (flag: boolean) => {
      if(flag) {
        ToastAndroid.show('锁车成功!', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show('锁车操作失败!', ToastAndroid.SHORT);
      }
    })
  }
  // 寻找车
  function searchBike() {
    updateBikeStatus(characteristic!, BluetoothCtrlBikeCommandEnum.寻车, (flag: boolean) => {
      if(flag) {
        ToastAndroid.show('寻车指令发送成功!', ToastAndroid.SHORT);
      } else {
        ToastAndroid.show('锁车操作失败!', ToastAndroid.SHORT);
      }
    })
  }

  function toRequestPermissions() {
    requestPermissions((flag: boolean) => {
      console.log('是否获取到了权限', flag);
      if(flag) {
        ToastAndroid.show('蓝牙权限获取成功!', ToastAndroid.CENTER);
      } else {
        ToastAndroid.show('蓝牙权限获取失败!', ToastAndroid.CENTER);
      }
    });
  }
  return (
    <View>
      <Text>搜索设备模式</Text>
      <View style={styles.btnBox}>
        <IconButton icon='check' label='获取蓝牙权限' onPress={toRequestPermissions} />
      </View>
      <View style={styles.btnBox}>
        <IconButton icon='search' label='扫描' onPress={scanDevices} />
      </View>
      <View style={styles.btnBox}>
        <IconButton icon='stop' label="停止扫描" onPress={stopScan} />
      </View>
      {
        connectedDevice?.name ?
        <View>
          <View style={styles.connectedBox}>
            <Text>已连接设备: {connectedDevice.name}</Text>
          </View>
          <View style={styles.btnBox}>
            <IconButton icon='bolt' label='启动' onPress={startBike} />
          </View>
          <View style={styles.btnBox}>
            <IconButton icon='https' label='锁车' onPress={lockBike} />
          </View>
          <View style={styles.btnBox}>
            <IconButton icon='notifications' label='寻车' onPress={searchBike} />
          </View>
          <View style={styles.btnBox}>
            <IconButton icon='cancel' label='断开连接' onPress={cancelConnectDevice} />
          </View>
        </View>
        :
        null
      }
      {dataArr.map((item, index) => {
        return (
          <TouchableOpacity key={index}>
            <View
              style={styles.item}>
              <Text>强度:{item.xinhao}</Text>
              <Text>名称：{item.name}</Text>
              <IconButton
                icon='timeline'
                label='连接'
                onPress={() => {
                  connectDevice(item);
                }} />
            </View>
            <View style={styles.itemBorder}></View>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}


const styles = StyleSheet.create({
  btnBox: {
    marginBottom: 20
  },
  item: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: 50
  },
  itemBorder: {
    borderWidth: 0.2, 
    borderColor: '#CCCCCC'
  },
  connectedBox: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    height: 50
  }
})